package com.ng.api.exterauth.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ng.api.exterauth.form.AppLoginForm;
import com.ng.api.exterauth.form.LogForm;
import com.ng.common.utils.PageUtils;
import com.ng.common.utils.R;
import com.ng.common.validator.ValidatorUtils;
import com.ng.common.validator.group.AddGroup;
import com.ng.exterauth.entity.SysExterAppEntity;
import com.ng.exterauth.entity.SysExterAppTokenEntity;
import com.ng.exterauth.service.SysExterAppService;
import com.ng.exterauth.service.SysExterAppTokenService;
import com.ng.exterauth.service.SysExterLogService;
import com.ng.security.exterauth.annotation.LoginApp;
import com.ng.security.exterauth.annotation.NoLogin;

//exapi
@RequestMapping("exapi")
@RestController
public class ApiController {

	@Autowired
	private SysExterAppService exterAppService ;
	
	@Autowired
	private SysExterAppTokenService tokenService;
	
	@Autowired
	private SysExterLogService logService ;
	
	
	@PostMapping("/login")
	@NoLogin
	public R<Object> login(@RequestBody AppLoginForm form) {
		
		ValidatorUtils.validateEntity(form, AddGroup.class);
		
		String ak = form.getAk();
		String sk = form.getSk();
		
		// 数据库按照AK 和SK 查找记录
		SysExterAppEntity app = exterAppService.queryByAkSk(ak, sk);
		if(app == null) {
			return R.error("AK/SK无效");
		}
		
		// 存在用户 更新token
		SysExterAppTokenEntity token = tokenService.generateToken(app.getId(), "app");
		
		Map<String, Object> map = new HashMap<>();
		map.put("token", token.getToken());
		map.put("expire", token.getExpireTime());
		
		return R.ok().setData(map);
	}
	
	@GetMapping("/log")
	public R<Object> logs(@LoginApp SysExterAppEntity app , LogForm form) {
		
		form.setAppname(app.getId());
		
		PageUtils pu = logService.queryPage(form);
		
		
		return R.ok().setData(pu);
	}
	
	
}

